import { baseURL } from './index.js'
/**
 * @function fetch请求封装
 *
 */
export async function http(url = '', data = {}, method = 'GET') {
	let response = null
	if (method == 'GET') {
		response = await fetch(baseURL + url + '?' + Qs.stringify(data), {
			method,
			headers: {
				'Content-Type': 'application/json',
			},
		})
	} else {
		response = await fetch(baseURL + url, {
			method,
			headers: {
				'Content-Type': 'application/json',
			},
			body: JSON.stringify(data),
		})
	}
	let result = await response.json()
	if (response.ok) {
		return result.data
	}
	message(`Status: ${response.status}`)
	throw 'response Error'
}

/**
 * @function 提示
 *
 */
export function message(msg = '请求成功', time = 2000) {
	const el = document.createElement('div')
	el.innerHTML = `<div class="message-view flex-alc">
        <div class="message">${msg}</div>
    </div>`
	el.className = 'me'
	document.body.appendChild(el)
	setTimeout(() => {
		document.querySelector('.me').remove()
	}, time)
}

/**
 * @function 防抖闭包
 *
 */
export function debounce(fun, wait = 300) {
	let timeout = null
	return function () {
		if (timeout) {
			clearTimeout(timeout)
		}
		timeout = setTimeout(() => {
			fun.apply(this, arguments)
			timeout = null
		}, wait)
	}
}

export const codeform = data => {
	console.log('codeform', data)
	const res = {
		url: data.url, //首页url
		chapterUrl: data.chapterUrl, //后续章节url
		title: data.title, //小说名
		chapter: data.chapter, // 章节数
		duwan: Number(data.duwan), //是否读完 0='未完' 1='读完'
		recommended: Number(data.recommended), // 是否是推荐 0='小说'  1='推荐'
		beizhu: data.beizhu,
		isdel: Number(data.isdel),
	}
	if (data.id) {
		res.id = data.id
	}
	return res
}

export const codeData = data => JSON.parse(JSON.stringify(data))

export const filterTitle = (list, title) => {
	return list.findIndex(iv => iv.title === title) >= 0 ? true : false
}

export const getbaseURL = () => {
	const development = ['127.0.0.1', 'localhost']
	const index = development.indexOf(window.location.hostname)
	return index > -1 ? 'http://localhost:4399' : 'https://456035ea.r1.cpolar.top'
}
